package com.braveo.dict;

import java.io.FileNotFoundException;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.Filterable;
import android.widget.TextView;

public class BraveDict extends Activity {
	//private VirtualKeyboard keyboard;
	//private BraveDictDbAdapter dbHelper;
    @SuppressWarnings("unused")
	private String [] wordList = new String []{};
    private WordListAdapter mWordListAdapter;
    @SuppressWarnings("unused")
	private boolean mWordListEnabled;
    private DictInitializer initializer;

	
	private static final int MENU_CHOOSE_DICT = Menu.FIRST;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.init(savedInstanceState);
        
    }
    
    private void chooseDict(){
        List<String> dbList = BraveDictDbAdapter.listDictDbs();
        if(dbList==null || dbList.size()==0){
        	showDialog(DictConst.DIALOG_NO_DB_ERROR);
        	return;
        }
        
        initializer.getDictMessageHandler().sendEmptyMessage(DictConst.MESSAGE_CHOOSE_DATABASE);    	
    }
    
    private void performSearch(){
    	TextView tv = (TextView)findViewById(R.id.edit_word);
		String word = tv.getText().toString().trim();
		tv.setText(word);	//Set the text back to the edit box
		if(word.length()==0){
			return;
		}
		
		//BraveRememberDbAdapter.getInstance(BraveDict.this).addHistory(word);
		
		Intent xs = new Intent(BraveDict.this, ExplanationView.class);
		xs.putExtra("WORD", word);
		startActivity(xs);   	
    }
    
    private synchronized void init(Bundle savedInstanceState){
    	
        setContentView(R.layout.main);
        
        //keyboard = new VirtualKeyboard(this);
        //keyboard.setInputTarget(this.findViewById(R.id.edit_word));

        final AutoCompleteTextView textView = (AutoCompleteTextView)findViewById(R.id.edit_word);
        textView.requestFocus();
        textView.setOnKeyListener(new View.OnKeyListener() {
        	public boolean onKey(View view, int k, KeyEvent keyEvent){
        		if(keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER){
        			performSearch();
        			return true;
        		}
        		return false;
        	}
        });
        
        textView.setOnFocusChangeListener(new View.OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){
					textView.selectAll();
				}
				
			}
        	
        });
        
        Button buttonSearch = (Button)findViewById(R.id.BSearch);
        
        buttonSearch.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View view){
        		performSearch();
        	}
        });
        
        Button buttonHistory = (Button)findViewById(R.id.BHistory);
        buttonHistory.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View view){
        		Intent xs = new Intent(BraveDict.this, HistoryView.class);
        		startActivityForResult(xs, DictConst.ACTIVITY_HISTORY);
        	}
        });
        
        Button buttonBook = (Button)findViewById(R.id.BBook);
        buttonBook.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View view){
        		chooseDict();
        	}
        });
        
        Button buttonClear = (Button)findViewById(R.id.BClear);
        buttonClear.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View view){
        		TextView tv = (TextView)findViewById(R.id.edit_word);
        		tv.setText("");
        	}
        });
        
        Button b = (Button)findViewById(R.id.BDrop);
        b.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View view){
        		AutoCompleteTextView tv = (AutoCompleteTextView)findViewById(R.id.edit_word);
        		tv.showDropDown();
        	}
        });

        showNotification();
        
        /*
        Intent x = new Intent(this, DatabaseChooseView.class);
        //startActivityForResult(x, ACTIVITY_CHOOSE_DB);
        this.startActivity(x);*/

        Context ctx = this.getApplicationContext();
        BraveDictDbAdapter.getInstance(ctx).addListener(new BraveDictDbAdapter.OnDictChanged(){

			public void afterChange(String oldDbName, String newDbName) {
				fillData();
			}

			public void beforeChange(String oldDbName, String newDbName) {				
				
			}

			public Object getOwner() {
				return BraveDict.this;
			}
        	
        });
        
        initializer = DictInitializer.getInitializer(this);
        try{
        	initializer.init();
        }catch(DictInitializer.InitialException e){
        	if(e.getError() == DictInitializer.InitError.DB_NOT_FOUND){
        		showDialog(DictConst.DIALOG_NO_DB_ERROR);
        		return;
        	}
        }        
        
                
        //set the keyboard invisible
        //keyboard.setVisibility(false);
    }
    
    protected Dialog onCreateDialog(int id){
    	switch(id) {
    	case DictConst.DIALOG_NO_DB_ERROR:
    		return new AlertDialog.Builder(BraveDict.this)
    			.setTitle("No Valid Dictionaries")
    			.setMessage("Brave Dictionary uses directionary database located in " 
    					+ BraveDictDbAdapter.DB_DIRECTORY + " with a prefix as BraveDict_ and a suffix as .db.\n" 
    					+ "For example: BraveDict_mydict.db\n\n"
    					+ "Please download the ditionaries first")
    			.setPositiveButton("OK", new DialogInterface.OnClickListener(){
    				public void onClick(DialogInterface dialog, int whichButton){
    					System.exit(0);
    				}
    			}).create();
    	}
    	return null;
    }

    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		Bundle extras = null;
		
		switch(requestCode){
		case DictConst.ACTIVITY_CHOOSE_DB:
			//mDictMessageHandler = null;
			if(data == null){
				BraveDictDbAdapter dbHelper = BraveDictDbAdapter.getInstance(this);
				if(dbHelper.getDatabaseName() != null)
					return;
				else
					System.exit(0);
			}
			extras = data.getExtras();
			String db_name = extras.getString("DB_NAME");
			if(db_name==null){
				finish();
			}
			try{
				BraveDictDbAdapter dbHelper = BraveDictDbAdapter.getInstance(this);
				if(dbHelper.getDatabaseName()!=null)
					dbHelper.close();
				dbHelper.setDbName(db_name);
				dbHelper.open();
				//fillData();
			}catch(FileNotFoundException fnfe){
				//should turn to runtime exception
				throw new RuntimeException(fnfe);
			}
			break;
		case DictConst.ACTIVITY_HISTORY:
			if(data == null){
				break;
			}
			extras = data.getExtras();

			String word = extras.getString("WORD");
			if(word!=null && word.length()!=0){
				AutoCompleteTextView v = (AutoCompleteTextView)findViewById(R.id.edit_word);
				v.setText(word);
			}
			break;
		}
		
	}
   
    private void enableWordListAdapter(boolean enable)
    {
        AutoCompleteTextView textView = (AutoCompleteTextView)findViewById(R.id.edit_word);
        //textView.setThreshold(1);
        if(enable){
        	textView.setAdapter(mWordListAdapter);
        }else{
        	textView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, new String [] {}));
        }
        textView.requestFocus();
        textView.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SPACE));        
        textView.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));        
    	mWordListEnabled = enable;
    }
    
   
    private void fillData()
    {
    	BraveDictDbAdapter dbHelper = BraveDictDbAdapter.getInstance(this);
    	//Cursor c = dbHelper.getAllWords();
    	Cursor c = dbHelper.getFewWords();
    	
    	this.startManagingCursor(c);
    	
    	mWordListAdapter = new WordListAdapter(this, c);
    	enableWordListAdapter(true);
    	
    	setDictName(dbHelper.getDatabaseShortName());
    	BraveConfigManager.getManager(getApplicationContext()).setDictName(dbHelper.getDatabaseShortName());
   }
    
    public static class WordListAdapter extends CursorAdapter implements Filterable{
    	private Context ctx;
    	
    	public WordListAdapter(Context context, Cursor c){
    		super(context, c);
    		ctx = context;
    	}
    	
    	@Override
    	public View newView(Context context, Cursor cursor, ViewGroup parent){
    		final LayoutInflater inflater = LayoutInflater.from(context);
    		//final TextView view = (TextView)inflater.inflate(R.layout.text_row, parent, false);
    		final TextView view = (TextView)inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
    		view.setText(cursor.getString(cursor.getColumnIndex("Word")));
    		//view.setTextSize(6.0f);
    		return view;
    	}
    	
    	@Override
    	public void bindView(View view, Context ctx, Cursor c){
    		((TextView)view).setText(c.getString(c.getColumnIndex("Word")));
    	}
    	
    	@Override
    	public String convertToString(Cursor c){
    		return c.getString(c.getColumnIndex("Word"));
    	}
    	
    	@Override
    	public Cursor runQueryOnBackgroundThread(CharSequence constraint){
    		if(getFilterQueryProvider() != null) {
    			return getFilterQueryProvider().runQuery(constraint);
    		}
    		
    		BraveDictDbAdapter dbHelper = BraveDictDbAdapter.getInstance(ctx);
    		return dbHelper.getWordByConstraint(constraint);
    	}
    }

    private void showNotification(){
    	
    	//disable notification
    	if(true)
    		return;
    	
    	NotificationManager nm = (NotificationManager)getSystemService(Activity.NOTIFICATION_SERVICE);
    	
    	CharSequence from = "BraveDict";
    	CharSequence message = "Look up your world. Yes, the world!";
    	
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, BraveDict.class), 0);
    	
    	String ticketText = "Brave Dict";
    	
    	Notification notif = new Notification(R.drawable.icon, ticketText, System.currentTimeMillis());
    	
    	notif.setLatestEventInfo(this, from, message, contentIntent);
    	
    	//notif.vibrate = new long[] { 100, 250, 100, 500 };
    	
    	nm.notify(R.string.app_name, notif);
    	
     }

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		/*synchronized(this){
			if(newConfig.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO){
				keyboard.setVisibility(false);
			}else{
				keyboard.setVisibility(true);
			}
		}*/
		
		
		
		super.onConfigurationChanged(newConfig);
	}
	
	public void setDictName(String dictName) {
		TextView tv = (TextView)this.findViewById(R.id.TVDatabaseName);
		tv.setText(dictName);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		//menu.add("Choose Dict");
		menu.add(0, MENU_CHOOSE_DICT, 0, "Choose Dict");
		
		return true;
	}

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
    	Intent x = null;
    	super.onOptionsItemSelected(item);
    	switch(item.getItemId()){
    	case MENU_CHOOSE_DICT:
    		chooseDict();
    		return true;
    	}
    	return true;
    }
}